package com.lsy.weizhi2.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.Poi;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.lsy.weizhi2.JsonObject.ActivityListObject;
import com.lsy.weizhi2.JsonObject.Classify;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.customview.HomeBottomItem;
import com.lsy.weizhi2.customview.MyVerticalViewPager;
import com.lsy.weizhi2.fragment.FuJingFragment;
import com.lsy.weizhi2.fragment.HomeFragment;
import com.lsy.weizhi2.fragment.PersonFragment;
import com.lsy.weizhi2.fragment.WeiYouFragment;
import com.lsy.weizhi2.getui.GeTuiFinal;
import com.lsy.weizhi2.getui.MyIntentService;
import com.lsy.weizhi2.getui.PushService;
import com.lsy.weizhi2.mybase.BaseApp;
import com.lsy.weizhi2.mybase.MyBaseActivity;
import com.lsy.weizhi2.mysql.MySQLOperate;
import com.lsy.weizhi2.third.LocationService;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class HomePage extends MyBaseActivity implements View.OnClickListener {
    private static Context context;
    private HomeFragment homeFragment;
    private FuJingFragment fuJingFragment;
    private WeiYouFragment weiYouFragment;
    private PersonFragment personFragment;
    private android.support.v4.app.FragmentManager manager;
    private FragmentTransaction ft;
    private FrameLayout home_frame;
    private ImageView home_send;
    private HomeBottomItem home_home, home_nearby, home_friend, home_person;
    //public static int flag=0;//展示的页面的id

    private static SharedPreferences sharedPreferences;
    private String permissionInfo;

    // PushService.class 个推（推送）-自定义服务名称, 核心服务
    private Class userPushService = PushService.class;
    private static final int REQUEST_PERMISSION = 0;


    public static Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Fresco.initialize(this);//放在加载布局之前
        setContentView(R.layout.activity_home_page);
        setTabSelection(MyInfo.HomeFlag);
        getPersimmions();
        InitPermission();
        parseManifests();
        Init();
    }

    List<ActivityListObject.ListBean> list;

    private void Init() {
        context = HomePage.this;

        sharedPreferences = getSharedPreferences(MyInfo.User_info, 0);
        MyInfo.ishomefirst = sharedPreferences.getBoolean("ishomefirst", true);
        if (MyInfo.User_Id == 0) {
            MyInfo.User_Id = sharedPreferences.getInt("user_id", 0);
        }

        MyInfo.Name = sharedPreferences.getString("name", "");
        if (MyInfo.Token == null) {
            MyInfo.Token = sharedPreferences.getString("token", "");
        }

        InitWidght();

        home_frame = (FrameLayout) findViewById(R.id.home_frame);
        fuJingFragment = new FuJingFragment();
        weiYouFragment = new WeiYouFragment();
        personFragment = new PersonFragment();
        homeFragment = new HomeFragment();
        manager = getSupportFragmentManager();
        showItem(MyInfo.HomeFlag);
    }

    private void InitWidght() {
        home_send = (ImageView) findViewById(R.id.home_send);
        home_home = (HomeBottomItem) findViewById(R.id.home_home);
        home_nearby = (HomeBottomItem) findViewById(R.id.home_nearby);
        home_friend = (HomeBottomItem) findViewById(R.id.home_friend);
        home_person = (HomeBottomItem) findViewById(R.id.home_person);
        home_send.setOnClickListener(this);
        home_home.setOnClickListener(this);
        home_nearby.setOnClickListener(this);
        home_friend.setOnClickListener(this);
        home_person.setOnClickListener(this);
    }

    private void showItem(int flag) {
        switch (flag) {
            case 0:
                SelectHome();
                break;
            case 1:
                SelectFuJing();
                break;
            case 2:
                SelectWeiYou();
                break;
            case 3:
                SelectPerson();
                break;
        }
    }

    /**
     * 主要用于获取关闭该页面时的保存位置信息
     *
     * @param savedInstanceState
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        Log.i("HomePage", "onRestore");
        MyInfo.HomeFlag = savedInstanceState.getInt("position");
        setTabSelection(MyInfo.HomeFlag);
        showItem(MyInfo.HomeFlag);
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void SelectPerson() {
        home_home.Change(R.mipmap.index_home1, false);
        home_nearby.Change(R.mipmap.index_nearby1, false);
        home_friend.Change(R.mipmap.index_friend1, false);
        home_person.Change(R.mipmap.index_my2, true);
        ft = manager.beginTransaction();
        ft.replace(R.id.home_frame, personFragment);
        ft.commit();
    }

    private void SelectWeiYou() {
        home_home.Change(R.mipmap.index_home1, false);
        home_nearby.Change(R.mipmap.index_nearby1, false);
        home_friend.Change(R.mipmap.index_friend2, true);
        home_person.Change(R.mipmap.index_my1, false);
        ft = manager.beginTransaction();
        ft.replace(R.id.home_frame, weiYouFragment);
        ft.commit();
    }

    private void SelectFuJing() {
        home_home.Change(R.mipmap.index_home1, false);
        home_nearby.Change(R.mipmap.index_nearby2, true);
        home_friend.Change(R.mipmap.index_friend1, false);
        home_person.Change(R.mipmap.index_my1, false);
        ft = manager.beginTransaction();
        ft.replace(R.id.home_frame, fuJingFragment);
        ft.commit();
    }

    private void SelectHome() {
        home_home.Change(R.mipmap.index_home2, true);
        home_nearby.Change(R.mipmap.index_nearby1, false);
        home_friend.Change(R.mipmap.index_friend1, false);
        home_person.Change(R.mipmap.index_my1, false);

        ft = manager.beginTransaction();
        ft.replace(R.id.home_frame, homeFragment);
        ft.commit();
    }

    /**
     * 主要用于保存该页面关闭时的位置信息
     *
     * @param outState
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //记录当前的position
        Log.i("HomePage", "onSave");
        outState.putInt("position", MyInfo.HomeFlag);
    }

    public void setTabSelection(int tabSelection) {
        MyInfo.HomeFlag = tabSelection;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.home_send:
                MyMethod.toActivity(context, SendNote.class);
                break;
            case R.id.home_home:
                SelectHome();
                MyInfo.HomeFlag = 0;
                break;
            case R.id.home_nearby:
                SelectFuJing();
                MyInfo.HomeFlag = 1;
                break;
            case R.id.home_friend:
                SelectWeiYou();
                MyInfo.HomeFlag = 2;
                break;
            case R.id.home_person:
                SelectPerson();
                MyInfo.HomeFlag = 3;
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.i("HomePage", "开始");
        getClassify();
    }

    private void getClassify() {
        MyOkHttpUtils.getInstance(context).doGet(Constants.GETORDERLIST, null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if (message != null) {
                            Gson gson = new Gson();
                            JSONArray jsonArray = null;
                            try {
                                jsonArray = new JSONArray(message);
                            } catch (JSONException e) {
                                Log.i("Welcome", "message=错误=1=" + message);
                            }

                            if (jsonArray != null && jsonArray.length() != 0) {
                                int length = jsonArray.length();
                                int nameSize = 0;
                                List<Classify.SecondCategoriesBean> list_c = new ArrayList<Classify.SecondCategoriesBean>();
                                for (int i = 0; i < length; i++) {
                                    Classify classify = null;
                                    try {
                                        classify = gson.fromJson(jsonArray.getJSONObject(i).toString(), Classify.class);
                                    } catch (JSONException e) {
                                        Log.i("Welcome", "message=错误=2=" + message);
                                    }

                                    int size = classify.getSecondCategories().size();
                                    nameSize += size;
                                    for (int j = 0; j < size; j++) {
                                        list_c.add(classify.getSecondCategories().get(j));
                                    }
                                }
                                Constants.name = new String[nameSize + 1];
                                for (int i = 0; i < nameSize; i++) {
                                    Constants.name[list_c.get(i).getId()] = list_c.get(i).getName();
                                }

                            }
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MyInfo.Token == null) {
            MyMethod.toActivity(context, LoginActivty.class);
            finish();
        }
        setTabSelection(MyInfo.HomeFlag);
        showItem(MyInfo.HomeFlag);
        Log.i("HomePage", "运行");
        /**
         * 该接口没数据，暂时屏蔽
         */
        if (!MyInfo.isActivity) {
            MyOkHttpUtils.getInstance(context).doGet(Constants.ActivityList, null)
                    .excute(new MyOkHttpUtils.OKCallBack() {
                        @Override
                        public void onFailure(String message) {

                        }

                        @Override
                        public void onResponse(String message) {
                            Log.e("HomePage", "message====" + message);
                            Gson gson = new Gson();
                            if (message != null) {
                                try {
                                    ActivityListObject activityListObject = gson.fromJson(message, ActivityListObject.class);
                                    list = activityListObject.getList();
                                    if (list != null && list.size() != 0) {
                                        final int size = list.size();
                                        Log.e("HomePage", "size==" + size);
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                for (int i = 0; i < size; i++) {
                                                    ActivityListObject.ListBean bean = list.get(i);
                                                    ContentValues values = new ContentValues();
                                                    values.put("id", bean.getId());
                                                    values.put("title", bean.getTitle());
                                                    values.put("content", bean.getContent());
                                                    values.put("name", bean.getRealName());
                                                    values.put("tel", bean.getTel());
                                                    values.put("create_time", bean.getCreateTime());
                                                    values.put("email", bean.getEmail());
                                                    values.put("enrollment", bean.getEnrollment());
                                                    values.put("photo", bean.getPhoto());
                                                    values.put("avatar", bean.getAvatar());
                                                    MySQLOperate.getInstance(context).Insert("activity", values, bean.getId());
                                                }
                                                MyInfo.isActivity = true;
                                            }
                                        }).start();
                                    }

                                } catch (Exception e) {
                                    Log.e("HomePage", "跳转");
                                    MyMethod.toActivity(context, LoginActivty.class);
                                }

                            }
                        }
                    });
        }
        if (BaseApp.GeTui_ClientId != null && BaseApp.GeTui_ClientId.length() != 0) {
            SendGeTuiCid();
        }
    }

    private void SendGeTuiCid() {
        MyOkHttpUtils.getInstance(context).doPost(Constants.SEND_GETUI_CID + "?cid=" + BaseApp.GeTui_ClientId, null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("HomePage", "message==" + message);
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("HomePage", "暂停");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("HomePage", "停止");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("HomePage", "销毁了");

    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /**
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), 127);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    //权限申请
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void InitPermission() {
        PackageManager pkgManager = getPackageManager();

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
        }

        // 注册 intentService 后 PushDemoReceiver 无效, sdk 会使用 DemoIntentService 传递数据,
        // AndroidManifest 对应保留一个即可(如果注册 DemoIntentService, 可以去掉 PushDemoReceiver, 如果注册了
        // IntentService, 必须在 AndroidManifest 中声明)
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), MyIntentService.class);

        // 应用未启动, 个推 service已经被唤醒,显示该时间段内离线消息
        if (BaseApp.linkedList != null) {
            //tLogView.append(Constant.payloadData);
        }
        // cpu 架构
        Log.d("HomePage", "cpu arch = " + (Build.VERSION.SDK_INT < 21 ? Build.CPU_ABI : Build.SUPPORTED_ABIS[0]));

        // 检查 so 是否存在
        File file = new File(this.getApplicationInfo().nativeLibraryDir + File.separator + "libgetuiext2.so");
        Log.e("HomePage", "libgetuiext2.so exist = " + file.exists());
    }

    //调用Manifests中的meta--提前编译保证在实例化个推前，相关数据到位
    private void parseManifests() {
        String packageName = getApplicationContext().getPackageName();
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                GeTuiFinal.appid = appInfo.metaData.getString("PUSH_APPID");
                GeTuiFinal.appsecret = appInfo.metaData.getString("PUSH_APPSECRET");
                GeTuiFinal.appkey = appInfo.metaData.getString("PUSH_APPKEY");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
